import {Component, ViewEncapsulation, ViewChild, OnInit, OnDestroy} from '@angular/core';
import {Content} from "@shared/components/toolbar/toolbar-content";
import {Router, NavigationEnd, NavigationStart, ActivatedRoute} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {StatisticsBaiduService} from "@core/statistics/baidu/statistics-baidu.service";
import {SeoService} from "@core/seo/seo.service";
import {SeoConfig} from "@core/seo/seo-config.modal";
import {SEO_CONFIG} from "@core/seo/seo.module";
import {WechatShareService} from "@core/wechat-share/wechat-share.service";
import {SharedService} from "@shared/service/shared/shared.service";
import 'rxjs/add/operator/pairwise';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit, OnDestroy {
  @ViewChild(Content) content;
  private _routeScrollPositions: { [url: string]: number } = {};
  private subscriptions: any;

  constructor(
    private router: Router,
    private tools: ToolsService,
    private baiduStatistics: StatisticsBaiduService,
    private _seoService: SeoService,
    private _wechatShareService: WechatShareService,
    private _sharedService: SharedService
  ) {

  }
/**
 * @description 二次分享
 * @author zhoukf 1349
 * */
  doWechatShare() {
    if (this.tools.ua().isWeixin) {
      this._wechatShareService.insertWechatJsSdk()
        .switchMap(res => {
          const url = encodeURIComponent(location.href.split('#')[0]);
          return this._sharedService.fetchWechatConfig(url);
        })
        .switchMap((res) => {
          this._wechatShareService.config(res.data);
          const param = {
            path: location.href
          };
          return this._sharedService.fetchShareData(param);
        })
        .filter(res => res.result === '0')
        .subscribe(res => {
          this._wechatShareService.updateShareData(res.data).onMenuShareAll();
      });
    }
  }

  ngOnInit() {
    this.baiduStatistics.buildBasic();
    this.doWechatShare();
    this.subscriptions = this.router.events.pairwise().subscribe(([prevRouteEvent, currRouteEvent]) => {
      if (prevRouteEvent instanceof NavigationEnd && currRouteEvent instanceof NavigationStart) {
        const content = document.getElementById('seed-scroll-content');
        const urlPath = (prevRouteEvent.urlAfterRedirects || prevRouteEvent.url ).split(';', 1)[0];
        this._routeScrollPositions[urlPath] = content && content.scrollTop || 0;
      } else if (currRouteEvent instanceof NavigationEnd) {
        setTimeout(() => {
          if (this.tools.ua().isWeixin) {
            this._wechatShareService.updateShareData({});
          }
          this.doWechatShare();
          const urlPath = (currRouteEvent.urlAfterRedirects || currRouteEvent.url).split(';', 1)[0];
          // 先获取上次缓存的值
          const top = this._routeScrollPositions[urlPath];

          // 有缓存值时才继续处理以减少dom操作
          if (top > 0) {
            const content = document.getElementById('seed-scroll-content');
            // 最后才获取scrollHeight以减小浏览器reflow的机率
            if (content && content.scrollHeight > top) {
              content.scrollTop = top;
            }
          }
        }, 0);
      }
    });
  }

  handleShare() {
    if (/Mobile/i.test(navigator.userAgent)) {
      this.handleShareOnPC();
    } else {
      this.router.navigate(['/']);
    }
  }

  handleShareOnPC() {
    const router = this.router;
    const params = location.search;
    const shareId = params.split('shareId=')[1];
    if (params.includes('product')) { // 商品
      router.navigate(['/goods/detail', shareId]);
    } else if (params.includes('coterie')) {
      router.navigate(['/community/circle', shareId]); // 圈子
    } else if (params.includes('community/detail')) {
      router.navigate(['/feed', shareId]); // 帖子
    } else {
      router.navigate(['/']);
    }
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }
}
